#抓取电影信息
import requests
import csv
import time
start = 0
top250_movie = []

while start < 250:
    
    try:
        url = 'https://api.douban.com/v2/movie/top250?start=' + str(start) + '&apikey=0df993c66c0c636e29ecbb5344252a4a'
        total_info = requests.get(url,headers={'user-agent':'chrome'})
        #print(dic_movie)
                
    except:
        print('获取失败')
    start += 20
    dic_url = total_info.json()
    
    list_movie = dic_url.get('subjects')
    for movie in list_movie:                                                                                                                                                                                                                                                                                                                                                                  
        #print(movie)
        id_movie = movie['id']
        title_movie = movie['title']
        rating_movie = movie['rating']['average']
        casts_movie = movie['casts']
        actor = []
        for j in casts_movie:
            actor.append(j['name']) 
        all_actor = ','.join(actor)
        image_movie = movie['images']['small']
        poster = requests.get(image_movie,headers={'user-agent':'chrome'})
        
        top250_movie.append([id_movie,title_movie,rating_movie,all_actor,image_movie])
        #print(top250_movie)
        time.sleep(1)

headers = ['编号','电影名称','评分','主演','海报链接']
    
try:
    with open('爬虫\\top250.csv','w',encoding='utf8',newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerow(headers)
        f_csv.writerows(top250_movie)
        
except:
    print('写入失败')

            
            
    

